package com.esunny.mina;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class KeepLiveMinaServer extends IoHandlerAdapter {

    private int                    port       = 8001;
    private Map<String, IoSession> ioSessions = new HashMap<String, IoSession>();

    public void start() throws IOException {
        IoAcceptor acceptor = new NioSocketAcceptor();

        acceptor.getFilterChain().addLast("logger", new LoggingFilter());

        acceptor.getFilterChain().addLast("codec",
                                          new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));

        acceptor.setHandler(this);

        acceptor.getSessionConfig().setReadBufferSize(2048);

        acceptor.bind(new InetSocketAddress(port));
        System.out.println(this.getClass().getCanonicalName() + " start listening port " + this.port);
        
        // System.out.println("Listeningon port " + PORT);
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        cause.printStackTrace();
        session.close(true);
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        System.out.println("message received in " + this.getClass().getCanonicalName() + " ..");

        String expression = message.toString();
        System.out.println("message :" + expression);

        IoSession shortConnSession = (IoSession) session.getAttribute("shortConnSession");

        System.out.println("ShortConnect Server Session ID =" + String.valueOf(shortConnSession.getId()));

        shortConnSession.write(expression);
        
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        System.out.println("disconnecting in idle.");
        session.close(true);
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        InetSocketAddress remoteAddress = (InetSocketAddress) session.getRemoteAddress();

        String clientIp = remoteAddress.getAddress().getHostAddress() + ":" + remoteAddress.getPort();
        System.out.println(clientIp + " connected");
        ioSessions.put(clientIp, session);
    }
}
